<?php
class AdImage extends AppModel {

	public $name         = 'AdImage';
    public $displayField = 'filename';
    public $belongsTo    = array(
        'AdPost' =>
            array(
                'className'  => 'AdPost',
                'foreignKey' => 'ad_post_id'
            )
    );

    public function deleteImage ($id, $path) {
        if (empty($id) || empty($path)) {
            return false;
        }

        $image = $this->findById($id, array('fields'=>'AdImage.filename, AdPost.id, AdPost.ad_image_id'));

        if (!$this->del($id)) {
            return false;
        }

        @unlink($path.$image['AdImage']['filename']);
        @unlink($path.'s_'.$image['AdImage']['filename']);

        if ($image['AdPost']['ad_image_id'] == $id) { // deleted image was default image in post
            $img = $this->findByAdPostId( // get another image from same post
                $image['AdPost']['id'],
                array('recursive'=>0, 'fields'=>'AdImage.id')
            );

            $newid = ($img['AdImage']['id']) ? $img['AdImage']['id'] : null;

            App::import('Model', 'AdPost');
            $AdPost = new AdPost();
            $AdPost->id = $image['AdPost']['id'];
            $AdPost->saveField('ad_image_id', $newid);
        }

        return true;
    } // deleteImage

} // AdImage
?>